//index.js
//获取应用实例
const app = getApp()
let Axios = require('../../common/js/ajax.js');
let Mtils = require('../../common/js/Mtils.min.js');
let webim = require('../../common/utils/webim_wx.js'); //腾讯云im包
let webimhandler = require('../../common/utils/webim_handler.js'); //这个是所有事件的腾讯js，这个页面需要用到登录
Mtils = Mtils.Mtils
var selSess = null;
var selType = webim.SESSION_TYPE.C2C;
var selToID, selSessHeadUrl;
var loginInfo = {
	'sdkAppID': app.data.Config.sdkappid, //用户所属应用id,必填
	'appIDAt3rd': app.data.Config.sdkappid, //用户所属应用id，必填
	'accountType': app.data.Config.accountType, //用户所属应用帐号类型，必填
	'identifier': app.globalData.identifier, //当前用户ID,必须是否字符串类型，选填
	'identifierNick': app.globalData.identifierNick, //当前用户昵称，选填
	'userSig': app.globalData.userSig, //当前用户身份凭证，必须是字符串类型，选填
};
Page({
	data: {
		openid: '',
		nickName: '',
		avatarUrl: '',
		curentNav: 2, //当前导航
		maskLogin: false,
		info: {}
	},
	//事件处理函数
	onLoad: function() {
		loginInfo = {
			'sdkAppID': 1400178898, //用户所属应用id,必填
			'appIDAt3rd': 1400178898, //用户所属应用id，必填
			'accountType': app.data.Config.accountType, //用户所属应用帐号类型，必填
			'identifier': app.globalData.identifier, //当前用户ID,必须是否字符串类型，选填
			'identifierNick': app.globalData.identifierNick, //当前用户昵称，选填
			'userSig': app.globalData.userSig, //当前用户身份凭证，必须是字符串类型，选填
		};
		var _this = this;
		this.login = this.selectComponent("#login");
		this.load = this.selectComponent("#loading");
		this.uid = app.globalData.uid || ''
		this.Md5 = Mtils.security.hex_md5(this.uid) + app.globalData.secret;
		this.Md5 = Mtils.security.hex_md5(this.Md5);
		this.timesp = Mtils.now();
		if (this.uid == '') {
			this.setData({
				maskLogin: true
			})
			_this.load.loadIng()
			return false
		} else {
			this.setData({
				maskLogin: false
			})
		}
		Axios.post(app.globalData.baseUrl + 'App/User/UserInfo/get_user_info', {
			uid: this.uid,
			time: this.timesp,
			sign: this.Md5,
		}, (res) => {
			console.log(res)
			if (res.status == 1) {
				var data = res.info
				_this.setData({
					info: data
				})
			} else {
				_this.showModal(res)
			}
		})
		if (app.globalData.nickName && app.globalData.avatarUrl) {
			_this.setData({
				nickName: app.globalData.nickName,
				avatarUrl: app.globalData.avatarUrl
			})
		}
	},
	onUnload() {
		//this.quitClick()
		console.log('onUnload')
	},
	onHide() {
		console.log('onHide')
		//this.quitClick()
	},
	onShow() {
		this.load.showIng()
		var _this = this;
		selToID = ''
		webimhandler.init({ //初始化的方法
			accountMode: app.data.Config.accountMode,
			accountType: app.data.Config.accountType,
			sdkAppID: 1400178898,
			selType: webim.SESSION_TYPE.C2C, //私聊
			id: selToID, //如果是经纪人，则填agent_member_id ,如果是普通用户则填经纪人id
			name: app.globalData.nickName,
			icon: app.globalData.avatarUrl,
			that: _this
		});
		if (webim.checkLogin()) { //检查是否登录返回true和false,不登录则重新登录
			console.log('已登录')
			_this.quitClick(function() {
				_this.sdkLogin(_this, app, selToID, function() {
					_this.initRecentContactList()
				});		
			})
			
		} else {
			console.log('登录成功')
			_this.sdkLogin(_this, app, selToID, function() {
				_this.initRecentContactList()
			});
		}
	},
	onReady: function() {
		wx.setNavigationBarTitle({
			title: '个人中心'
		})
	},
	preventTouchMove: function() {},
	bubbling: function() {},
	handleMaskTap: function() {
		this.login.showIng()
	},
	handleShopTap: function(e) {
		var _this = this
		var id = this.data.info.store_id;
		var status = this.data.info.status
		var type = e.currentTarget.dataset.type;
		if (id > 0) {
			if (type == 0) {
				if (status == 1) {
					var temp = {
						subject: _this.data.info.subject_property,
						store_id: _this.data.info.store_id,
						store_title: _this.data.info.store_title,
						store_icon: _this.data.info.store_icon,
						description: _this.data.info.description,
						address: _this.data.info.address,
						balance: _this.data.info.balance,
						fans: _this.data.info.fans,
						store_ava_point: _this.data.info.store_ava_point,
						share_content: _this.data.info.share_content,
						subject_property: _this.data.info.subject_property,
						address: _this.data.info.address,
						bond_icon: _this.data.info.bond_icon
					}
					app.globalData.temp = temp
					wx.navigateTo({
						url: '/pages/myShop/myShop'
					})
				} else {
					if (status == 2) {
						wx.showModal({
							content: '审核失败,请重新提交',
							showCancel: false
						})
					}
					if (status == 3) {
						wx.showModal({
							content: '店铺正在审核,请耐心等待',
							showCancel: false
						})
					}
				}
			} else {
				wx.navigateTo({
					url: '/pages/applyShop/applyShop?id=' + this.data.info.store_id
				})
			}
		} else {
			this.setData({
				shopTk: true
			})
		}
	},
	cancelTk: function() {
		this.setData({
			shopTk: false
		})
	},
	handleOpenTap: function(e) {
		var id = this.data.info.store_id;
		wx.navigateTo({
			url: '/pages/applyShop/applyShop'
		})
	},
	showModal: function(error) {
		wx.showModal({
			content: error.msg,
			showCancel: false,
		})
	},
	initRecentContactList: function() {
		var that = this;
		webim.syncMsgs();
		var sessMap = webim.MsgStore.sessMap();
		var num = 0
		setTimeout(function() {
			for (var i in sessMap) {
				num += sessMap[i].unread()
			}
			that.setData({
				numChat: num
			}, function() {
				that.load.loadIng()			
			})
		}, 1000)
	},
	sdkLogin: function(that, app, selToID, callback) {
		var that = this
		if (!callback) {
			callback = () => {}
		}
		//1v1单聊的话，一般只需要 'onConnNotify' 和 'onMsgNotify'就行了。
		//监听连接状态回调变化事件
		var onConnNotify = function(resp) {
			switch (resp.ErrorCode) {
				case webim.CONNECTION_STATUS.ON:
					webim.Log.warn('连接状态正常...');
					break;
				case webim.CONNECTION_STATUS.OFF:
					webim.Log.warn('连接已断开，无法收到新消息，请检查下你的网络是否正常');
					break;
				default:
					webim.Log.error('未知连接状态,status=' + resp.ErrorCode);
					break;
			}
		};
		var onMsgNotify = function(msg) {

		}
		//监听事件
		var listeners = {
			"onConnNotify": onConnNotify, //监听连接状态回调变化事件,必填			
			"onMsgNotify": onMsgNotify
		};
		//其他对象，选填
		var options = {
			'isAccessFormalEnv': true, //是否访问正式环境，默认访问正式，选填
			'isLogOn': false //是否开启控制台打印日志,默认开启，选填
		};
		//sdk登录(独立模式)
		webim.login(loginInfo, listeners, options, function(resp) {
			callback()
		}, function(err) {
			console.log("登录失败", err.ErrorInfo)
		});
	},
	quitClick: function(callback) {
		if (loginInfo.identifier) {
			//sdk登出
			webim.logoutAll(callback, function(res) {
				console.log(res)
			});
		} else {
			// alert('未登录');
		}
	}
})
